
// packageC/pages/wait_pay/wait_pay.js
import { ml_hideLoading, ml_showLoading, ml_showToast, ml_Toast } from '../../../utils/asyncWX'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    order_list: []
  },
  async getdata() {
    let openid = wx.getStorageSync('openid');
    var DB = wx.cloud.database();
    const _ = DB.command;
    // 等待支付订单
    var res1 = await DB.collection('wait_pay').get();
    // 优惠卷？
    var res2 = await DB.collection('login_coupon').where({ login_openid: openid, over_time: _.gte(+new Date()) }).get();
    console.log(res1.data);
    console.log(res2.data);
    //处理优惠卷
    var pay_number, orsder_id = '', coupon_id = '';
    for (let i = 0; i < res1.data.length; i++) {
      pay_number = res1.data[i].pay_aftermoney;
      orsder_id = res1.data[i]._id;
      for (let j = 0; j < res2.data.length; j++) {
        //结束时间大于现在
        if (res1.data[i].type_order == res2.data[j].collar_inf.type_order) {  //应用类型
          if (res1.data[i].type_order == 'sender') {  // 使用类型
            if (res2.data[j].collar_inf.user_type == 'deduction') {
              //需支付金额 - 抵扣
              pay_number = Number(res1.data[i].pay_aftermoney) - Number(res2.data[j].collar_inf.order_number);
              //记录订单id和使用的优惠卷id核对数据
              orsder_id = res1.data[i]._id; coupon_id = res2.data[j]._id;
            } else if (res2.data[j].collar_inf.user_type == 'discount') {
              //需支付金额 * 折扣
              pay_number = Number(res1.data[i].pay_aftermoney) * (Number(res2.data[j].collar_inf.order_number) * 0.1);
              //记录订单id和使用的优惠卷id核对数据
              orsder_id = res1.data[i]._id; coupon_id = res2.data[j]._id;
            }
          } else if (res1.data[i].type_order == 'collection') {
            if (res2.data[j].collar_inf.user_type == 'deduction') {
              //需支付金额 - 抵扣
              pay_number = Number(res1.data[i].pay_aftermoney) - Number(res2.data[j].collar_inf.order_number);
              //记录订单id和使用的优惠卷id核对数据
              orsder_id = res1.data[i]._id; coupon_id = res2.data[j]._id;
            } else if (res2.data[j].collar_inf.user_type == 'discount') {
              //需支付金额 * 折扣
              pay_number = Number(res1.data[i].pay_aftermoney) * (Number(res2.data[j].collar_inf.order_number) * 0.1);
              //记录订单id和使用的优惠卷id核对数据
              orsder_id = res1.data[i]._id; coupon_id = res2.data[j]._id;
            }
          }
        }
      }
      res1.data[i]['pay_last'] = Math.round(pay_number * 100) / 100;   //卷抵扣最终付款数
      let pay_count = res1.data[i].pay_aftermoney - res1.data[i].pay_last;
      res1.data[i]['pay_count'] = Math.round(pay_count * 100) / 100;  //卷抵扣钱数
      res1.data[i]['orsder_id'] = orsder_id; res1.data[i]['coupon_id'] = coupon_id;
    }
    console.log(res1.data);
    console.log(res2.data);
    this.setData({ order_list: res1.data.reverse() });
  },
  //取消订单
  order_out(e) {
    let ids = e.currentTarget.dataset.id;
    console.log(e.currentTarget.dataset.id);
    const that = this;
    wx.showModal({
      title: '取消后无法恢复',
      content: '你确定要取消这个订单吗？',
      success(res) {
        if (res.confirm) {
          //删除订单
          wx.cloud.callFunction({
            name: 'getorder_list', data: {
              type: 'mail_delect',
              id: ids
            }
          }).then(res => {
            console.log(res)
            ml_showToast('取消成功！');
            that.getdata();
          }).catch(res => {
            console.log(res)
            ml_Toast('取消失败！请重新尝试！')
          })
        }
      }
    })
  },
  //支付函数
  async payment(value) {
    //拉起支付
    console.log(value)
    let res = await wx.cloud.callFunction({
      name: 'payment', data: {
        type:'pay_money',
        orderid: value.orderid,
        money: value.money * 100, //分做单位的
        title: value.title
      }
    })
    let res1 = await wx.requestPayment({
      timeStamp: res.result.timeStamp,
      nonceStr: res.result.nonceStr,
      package: res.result.package,
      signType: 'MD5',
      paySign: res.result.paySign,
    })
    if (res1.errMsg == "requestPayment:ok") {
      ml_showToast('支付成功');
      return { 'code': 200, 'datas': res1 };
    } else {
      ml_Toast('支付失败！请重新尝试支付！');
      return { 'code': 400, 'datas': res1 };
    }
  },


  //去支付
  async paymoney(e) {
    let items = e.currentTarget.dataset.item;
    // try {
      //核对价格
      ml_showLoading();
      let res1 = await wx.cloud.callFunction({
        name: 'pass_coupon', data: {
          type: 'hedui', orsder_id: items.orsder_id, coupon_id: items.coupon_id
        }
      })
      if (res1.result.return_data.code == 200) {
        //提交价格支付
        let timeString = +new Date();
        let value = {
          orderid: timeString + 'gold',
          money: Number(res1.result.return_data.pay_number),
          title: '一运校园物流收款专用'
        }
        let datas = {
          pay_time: timeString,         //支付时间
          order_number: timeString + 'gold',              //订单号
          pay_orderinf: res1.result.orsder_data.pay_orderinf,          //订单详情
          need_pay: Number(res1.result.orsder_data.pay_aftermoney),          // 需支付金额
          pay_money: Number(res1.result.return_data.pay_number),           //实付金额
          pay_store_inf: { 'pay_store_weight': res1.result.orsder_data.pay_store_weight, 'pay_store_inf': res1.result.orsder_data.pay_store_inf },                          //物品信息
          pay_courier_inf: res1.result.orsder_data.pay_courier_inf,            //快递员信息
          rider_id: res1.result.orsder_data.rider_id,              //快递员识别号
          coupon_inf: res1.result.coupon_data,              // 优惠卷信息
          order_code:0,    //订单状态码
          order_state: [{'state':'已支付','state_title':'骑手已接单，开始运送','pay_time':timeString}],                                 //订单状态
          ifover_order: false                            //是否签收
        }
        //支付函数
        console.log(value);
        let pay_result;
        try {
          pay_result = await this.payment(value);
        } catch (error) {
          console.log(error);
        }

        console.log(pay_result)
        if (pay_result.code == 200) {
          //支付成功记录数据库
          let res2 = await wx.cloud.database().collection('login_orderList').add({ data: datas });
          //删除待支付订单  删除待支付订单和用户优惠卷。
          console.log(res1);
          let res3 = await wx.cloud.callFunction({
            name: 'pass_coupon', data: {
              type: 'delect',
              orsder_data_id: res1.result.orsder_data._id,
              coupon_data_id: res1.result.coupon_data == '' ? '' : res1.result.coupon_data._id,
            }
          })
          console.log(res2);
          console.log(res3);
        }
        // 成功后更新数据
        this.getdata();
        ml_hideLoading();

      } else {
        ml_Toast(res1.result.return_data.text);
      }
    // } catch (error) {
    //   ml_Toast('支付失败，请重新尝试！');
    //   console.log(error);
    // }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getdata();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})